package com.yangtao.framework.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;

/**
 * 资源文件读写器
 *
 * @创建者:杨涛
 * @创建时间:2009-07-04
 * @修改者:
 * @修改时间:
 * @修改原因:
 * @版本:1.2
 */
public class ResourceLoader {
	private static ResourceLoader instance = new ResourceLoader();
	@SuppressWarnings("unchecked")
	private static HashMap cache = new HashMap();

	public static ResourceLoader getInstance() {
		return instance;
	}

	@SuppressWarnings("unchecked")
	public InputStream getResource(String s) {
		InputStream ret = null;
		if (cache.containsKey(s)) {
			ret = (InputStream) cache.get(s);
		} else {
			ret = resourceReader(s);
			cache.put(s, ret);
		}
		return ret;
	}

	public Document getDom(String s) {
		Document ret = null;
		if (cache.containsKey(s)) {
			ret = (Document) cache.get(s);
		} else {
			ret = domReader(s);
		}
		return ret;
	}

	private InputStream resourceReader(String s) {
		return Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(s);
	}

	private Document domReader(String s) {
		Document doc = null;
		SAXReader reader = new SAXReader();
		try {
			doc = reader.read(resourceReader(s));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return doc;
	}
}
